<template>
  <el-dialog title="自定义节点" :visible.sync="dialogVisible">
    <el-form :model="form" :rules="formRules" ref="ruleForm">
      <el-form-item label="节点名称" :label-width="formLabelWidth" prop="nodeName">
        <el-input v-model="form.nodeName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="所属分组" :label-width="formLabelWidth" prop="nodeGroup">
        <el-select v-model="form.nodeGroup" placeholder="请选择所属分组">
          <el-option v-for="item of nodeGroups" :key="item.name" 
            :label="item.title" :value="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="节点类型" :label-width="formLabelWidth" prop="nodeType">
        <el-select v-model="form.nodeType" placeholder="请选择节点类型">
          <el-option v-for="item of metaTypes" :key="item.value" 
            :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>      
      <el-form-item label="节点描述" :label-width="formLabelWidth" prop="nodeDesc">
        <el-input v-model="form.nodeDesc" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleClick">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import ConfigUtil from '@/utils/graph-utils/configUtil.js'

export default {
  name: 'CustomNodeDialog',
  data() {
    var validateNodeName = (rule, value, callback) => {
      console.log('validateNodeName', this)
      const registerNodeNames = this.$store.state.nodeModule.registerNodeNames
      if (!value) {
        return callback(new Error('节点名称不能为空'))
      }
      if (registerNodeNames.indexOf(value) !== -1) {
        return callback(new Error('节点名称已存在'))
      }
      callback()
    }

    return {
      dialogVisible: false,

      form: {
        nodeName: '',
        nodeGroup: '',
        nodeType: '',
        nodeDesc: ''
      },
      formRules: {
        nodeName: [
          { required: true, validator: validateNodeName, trigger: 'blur' }
        ],
        nodeGroup: [
          { required: true, message: '请选择所属分组', trigger: 'change' }
        ],
        nodeType: [
          { required: true, message: '请选择节点类型', trigger: 'change' }
        ],
        nodeDesc: [
          { required: true, message: '请选择节点描述', trigger: 'change' }
        ]
      },
      formLabelWidth: '120px'
    }
  },
  computed: {
    nodeGroups: function() {
      return ConfigUtil.getStencilGroups()
    },

    metaTypes: function() {
      return ConfigUtil.getMetaTypes()
    }
  },
  methods: {
    showDialog() {
      this.dialogVisible = true
    },

    handleClick() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.dialogVisible = false
          this.$emit('submitOk', this.form)
        } else {
          return false
        }
      })
    }
  }
}
</script>